package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.feign.client.ArticleFeignClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author Gareth Cao
 * @date 2022/6/24 20:42
 */

/**
 * 自媒体文章审核实现类
 */
@Service
@Transactional
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ArticleFeignClient articleFeignClient;

    @Autowired
    private WmChannelMapper wmChannelMapper;

    @Autowired
    private WmUserMapper wmUserMapper;

    /**
     * 自媒体文章审核
     *
     * @param newsId 自媒体文章id
     */
    @Override
    @Async // 异步线程调用
    public void autoScanWmNews(Integer newsId) throws Exception {
        //1 查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(newsId);
        if (wmNews == null) {
            return;
        }
        //1.1 抽取文本和图片
        Map<String, Object> map = extractImageAndText(wmNews);
        //1.2 在提交阿里云审核之前先自管理敏感词
        Boolean flag = sensitiveText((String) map.get("text"));
        if (!flag) {
            //不通过
            return;
        }

        //2 文章文本审核
        Map textMap = greenTextScan.greeTextScan((String) map.get("text"));
        if (textMap.get("suggestion").equals("block")) {
            //违规，修改wm_news状态为2
            updateWmNews(wmNews, (short) 2, "文章内容有违规内容");
            return;
        } else if (textMap.get("suggestion").equals("review")) {
            updateWmNews(wmNews, (short) 3, "文章需要人工审核");
            return;
        }
        //3 文章图片审核
        List<String> imagesList = (List<String>) map.get("imagesList");
        if (imagesList != null) {
            List<byte[]> byteList = new ArrayList<>();
            for (String path : imagesList) {
                byte[] bytes = fileStorageService.downLoadFile(path);
                byteList.add(bytes);
            }
            Map imageMap = greenImageScan.imageScan(byteList);
            if (imageMap.get("suggestion").equals("block")) {
                //违规，修改wm_news状态为2
                updateWmNews(wmNews, (short) 2, "图片内容有违规内容");
                return;
            } else if (imageMap.get("suggestion").equals("review")) {
                updateWmNews(wmNews, (short) 3, "图片需要人工审核");
                return;
            }
        }

        //4 远程调用保存三剑客的接口
        ResponseResult responseResult = saveArticleWithWmNews(wmNews);
        //5 更新wm_news表
        wmNews.setArticleId(Long.parseLong(responseResult.getData().toString()));
        updateWmNews(wmNews, (short) 9, "发布成功");
    }

    /**
     * 自管理敏感词
     *
     * @param text
     * @return
     */
    private Boolean sensitiveText(String text) {
        //1 查询敏感词列表
        //2 初始化敏感词列表
        //3 校验敏感词，返回map
        //4 返回数据
        return null;
    }

    /**
     * 第三个方法
     *
     * @param wmNews
     * @return
     */
    private ResponseResult saveArticleWithWmNews(WmNews wmNews) {
        ArticleDto dto = new ArticleDto();
        BeanUtils.copyProperties(wmNews, dto);
        dto.setLayout(wmNews.getType());
        WmChannel wmChannel = wmChannelMapper.selectById(wmNews.getChannelId());
        if (wmChannel != null) {
            dto.setChannelName(wmChannel.getName());
        }

        //作者
        dto.setAuthorId(wmNews.getUserId().longValue());
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (wmUser != null) {
            dto.setAuthorName(wmUser.getName());
        }

        //设置文章id
        if (wmNews.getArticleId() != null) {
            dto.setId(wmNews.getArticleId());
        }
        dto.setCreatedTime(new Date());

        ResponseResult responseResult = articleFeignClient.saveArticle(dto);
        return responseResult;
    }

    /**
     * 抽取第二个方法
     *
     * @param wmNews
     * @param i
     * @param message
     */
    private void updateWmNews(WmNews wmNews, Short i, String message) {
        wmNews.setStatus(i);
        wmNews.setReason(message);
        wmNewsMapper.updateById(wmNews);
    }

    /**
     * 抽取的第一个方法
     *
     * @param wmNews
     */
    private Map<String, Object> extractImageAndText(WmNews wmNews) {
        // 声明一个字符串 用来封装文本
        StringBuffer stringBuffer = new StringBuffer();
        // 声明一个集合，用来封装图片地址
        List<String> imagesList = new ArrayList<>();
        //先获取文本
        String title = wmNews.getTitle();
        stringBuffer.append(title);
        //获取封面图片地址
        String images = wmNews.getImages();
        if (images != null && !"".equals(images)) {
            String[] split = images.split(",");
            imagesList.addAll(Arrays.asList(split));
        }
        //获取内容
        String content = wmNews.getContent();
        List<Map> contentList = JSON.parseArray(content, Map.class);
        for (Map map : contentList) {
            if (map.get("type").equals("text")) {
                //文本
                String value = (String) map.get("value");
                stringBuffer.append(value);
            }
            if (map.get("type").equals("image")) {
                //图片地址
                String path = (String) map.get("value");
                imagesList.add(path);
            }
        }

        Map<String, Object> hashMap = new HashMap<>();
        hashMap.put("text", stringBuffer.toString());
        hashMap.put("imagesList", imagesList);
        return hashMap;
    }
}
